package convert

import (
	"goapp/internal/models"
	"regexp"
	"strconv"
	"strings"
	"time"
)

const TimeLayout = "2006-01-02 15:04:05"
const TimeLayoutMS = "2006-01-02 15:04:05.000"
const SubTitle = "Press Enter to paste, or Cmd+C to copy."

func Convert(str string) []models.AlfredItem {
	// 创建一个表示东8区的 Location 对象
	loc, _ := time.LoadLocation("Asia/Shanghai")
	// 要返回的数据
	items := make([]models.AlfredItem, 0)
	// 匹配时间的政策
	dateTimeRegex := regexp.MustCompile("^([0-9-]{10}[\\sT][0-9:]{8})(\\.(\\d{1,6}))?$")

	if regexp.MustCompile("^\\d{10}$").MatchString(str) {
		// 匹配时间戳秒ok,1234567890
		argTime := time.Unix(convertInt64(str), 0)
		itemStr := argTime.Format(TimeLayout)
		items = append(items, models.AlfredItem{Uid: itemStr, Title: itemStr, Arg: itemStr, Subtitle: SubTitle})
	} else if regexp.MustCompile("^\\d{13}$").MatchString(str) {
		// 匹配时间戳毫秒ok,1234567890123
		argTime := time.UnixMilli(convertInt64(str))
		itemStr := argTime.Format(TimeLayoutMS)
		items = append(items, models.AlfredItem{Uid: itemStr, Title: itemStr, Arg: itemStr, Subtitle: SubTitle})
	} else if dateTimeRegex.MatchString(str) {
		timeMatch := dateTimeRegex.FindStringSubmatch(str)
		// 替换时间里的T为" "
		dateTimeStr := strings.Replace(timeMatch[1], "T", " ", 1)
		// 匹配中文时间ok,2024-10-10 01:00:01
		parsedTime, _ := time.ParseInLocation(TimeLayout, dateTimeStr, loc)
		// group3是毫秒段
		msStr := timeMatch[3]
		if len(msStr) > 0 {
			// 把毫秒数添加到时间里去
			msInt := convertInt64(msStr)
			if msInt <= 999 {
				// 毫秒
				parsedTime = parsedTime.Add(time.Duration(msInt) * time.Millisecond)
			} else {
				// 微秒
				parsedTime = parsedTime.Add(time.Duration(msInt) * time.Microsecond)
			}
		}
		// 转时间戳秒
		itemStr := strconv.FormatInt(parsedTime.Unix(), 10)
		items = append(items, models.AlfredItem{Uid: itemStr, Title: itemStr, Arg: itemStr, Subtitle: SubTitle})
		// 转时间戳毫秒
		itemStr2 := strconv.FormatInt(parsedTime.UnixMilli(), 10)
		items = append(items, models.AlfredItem{Uid: itemStr2, Title: itemStr2, Arg: itemStr2, Subtitle: SubTitle})
	} else {
		// 显示当前时间
		parsedTime := time.Now()
		// 转时间格式
		itemStr3 := parsedTime.Format(TimeLayout)
		items = append(items, models.AlfredItem{Title: "当前时间:" + itemStr3, Arg: itemStr3, Subtitle: SubTitle})
		// 转时间戳毫秒
		itemStr2 := strconv.FormatInt(parsedTime.UnixMilli(), 10)
		items = append(items, models.AlfredItem{Title: "当前时间戳(ms):" + itemStr2, Arg: itemStr2, Subtitle: SubTitle})
		// 转时间戳秒
		itemStr := strconv.FormatInt(parsedTime.Unix(), 10)
		items = append(items, models.AlfredItem{Title: "当前时间戳(s):" + itemStr, Arg: itemStr, Subtitle: SubTitle})
	}
	return items
}

func convertInt64(str string) int64 {
	var val int64 = 0
	val, _ = strconv.ParseInt(str, 10, 64)
	return val
}
